﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using SD.LLBLGen.Pro.ORMSupportClasses;

using VitalShining.WebControls;
using CARMSBusiness;
using CARMSBusiness.InterFace;
using CARMSData.CollectionClasses;
using CARMSData.EntityClasses;
using CARMSData.HelperClasses;



namespace CARMS
{

    #region Attributes
    public class FunctionAttribute : Attribute
    {
        public FunctionAttribute(string functionId)
        {
            FunctionID = functionId;
        }
        public string FunctionID { get; private set; }
    }

    [Serializable]
    public class UserData
    {
        public int UserID { get; set; }
        public string LoginName { get; set; }
        public string UserName { get; set; }
    }


    [Serializable]
    public class ManualItem
    {
        public string Name { get; set; }
        public string Value { get; set; }

    }
    #endregion

    public class PageBase : VSPage
    {
        public string strSeperator = ",";
        public string ConstEmailUploadFolder = "~/Files/Email/";
        public string FileUploadFolder = "~/Files/";

        public string FileImageFolder = "~/upload/images/";
        public string FileQuotationFolder = "~/Files/Quotation/";


        public string RequestUrl
        {
            get
            {
                return Server.UrlEncode(Request.Url.ToString());
            }
        }

        #region cookies 保存用户名


        //public void SetCookieUserID(Guid userID)
        //{
        //    HttpCookie cookie = Request.Cookies.Get("LIMSUserInfo");
        //    if (cookie != null)
        //    {
        //        cookie.Values["UserID"] = userID.ToString();
        //        cookie.Value = DateTime.Now.ToString();
        //        cookie.Expires = DateTime.Now.AddDays(30);
        //        Response.Cookies.Add(cookie);
        //    }

        //}


        #endregion

        #region session
        public UserData CurrentLoginUser
        {
            get
            {
                if (Session["CurrentLoginUser"] == null)
                {

                    Session["CurrentLoginUser"] = new UserData
                                                      {
                                                          UserID = 0,
                                                          UserName = string.Empty,
                                                          LoginName = string.Empty
                                                      };

                }
                return (UserData)Session["CurrentLoginUser"];
            }
            set
            {
                Session["CurrentLoginUser"] = value;
            }
        }

        public string CurrentCulture
        {
            get
            {
                if (Session["CurrentCulture"] == null)
                {
                    Session["CurrentCulture"] = CultureNames.Chinese;

                }
                return Session["CurrentCulture"].ToString();
            }
            set
            {
                Session["CurrentCulture"] = value;
            }
        }

        public bool MenuLoaded
        {
            get
            {
                if (Session["MenuLoaded"] == null)
                {
                    Session["MenuLoaded"] = false;
                }
                return (bool)Session["MenuLoaded"];
            }
            set
            {
                Session["MenuLoaded"] = value;
            }
        }

        public MailData CurrentMailData
        {
            get
            {
                if (Session["CurrentMailData"] == null)
                {
                    return null;
                }
                return (MailData)Session["CurrentMailData"];

            }
            set { Session["CurrentMailData"] = value; }
        }

        #endregion
        #region General info
        protected virtual string CurrentFunction
        {
            get
            {
                var attr = (FunctionAttribute)TypeDescriptor.GetAttributes(this)[typeof(FunctionAttribute)];
                return attr == null ? string.Empty : attr.FunctionID;
            }
        }
        #endregion

        protected void RediretResolveUrl(string strUrl)
        {
            Response.Redirect(ResolveUrl(strUrl));
        }


        public string GetUserName(int dataValue)
        {
            var data = new UserEntity(dataValue);
            if (data.IsNew)
            {
                return string.Empty;
            }
            else
            {
                return data.FullName;
            }
        }
        public string GetDataName(int? dataValue)
        {
            if (dataValue.HasValue)
            {
                return GetDataName(dataValue.Value);
            }
            return string.Empty;
        }

        public string GetDataName(int dataValue)
        {
            var data = new DictionaryEntity(dataValue);
            if (data.IsNew)
            {
                return string.Empty;
            }
            else
            {
                return data.Name;
            }
        }



        ///// <summary>
        ///// 根据userid 取 employee name
        ///// </summary>
        ///// <param name="dataValue"></param>
        ///// <returns></returns>
        //public string GetEmployeeName(Guid dataValue)
        //{

        //    var data = new UserEntity(dataValue);
        //    if (!data.IsNew)
        //    {
        //        if (data.EmployeeId.HasValue)
        //        {
        //            var empEntity = new EmployeeEntity(data.EmployeeId.Value);
        //            if (!empEntity.IsNew)
        //            {
        //                return empEntity.FirstName + " " + empEntity.LastName;
        //            }
        //        }
        //    }

        //    return string.Empty;
        //}

        //public string GetContactNameByContactID(Guid dataValue)
        //{
        //    var entity = new ContactEntity(dataValue);
        //    if (!entity.IsNew)
        //    {
        //        return entity.ContactName;
        //    }
        //    return string.Empty;
        //}

        /// <summary>
        /// 根据user id 取emp id
        /// </summary>
        /// <param name="dataValue"></param>
        /// <returns></returns>
        //public Guid GetEmployeeID(Guid dataValue)
        //{

        //    var data = new UserEntity(dataValue);
        //    if (!data.IsNew)
        //    {
        //        if (data.EmployeeId.HasValue)
        //        {
        //            return data.EmployeeId.Value;
        //        }
        //    }

        //    return Guid.Empty;
        //}


        //public EmployeeEntity GetEmployeeByUserID(Guid dataValue)
        //{

        //    var data = new UserEntity(dataValue);
        //    if (!data.IsNew)
        //    {
        //        if (data.EmployeeId.HasValue)
        //        {
        //            var empEntity = new EmployeeEntity(data.EmployeeId.Value);
        //            if (!empEntity.IsNew)
        //            {
        //                return empEntity;
        //            }
        //        }
        //    }
        //    return null;
        //}


        // public string GetCurrencyName(Guid? dataValue)
        // {
        //     if (dataValue.HasValue)
        //     {
        //         var entity = new CurrencyEntity(dataValue.Value);
        //         if (!entity.IsNew)
        //         {
        //             return entity.CurrencyName;
        //         }
        //     }
        //     return string.Empty;
        // }

        //public string GetSampleName(Guid sampleID)
        //{
        //    var entity = new SampleEntity(sampleID);
        //    if(!entity.IsNew)
        //    {
        //        return entity.SampleName;
        //    }
        //    return string.Empty;
        //}


        //public string GetServiceName(Guid serviceID)
        //{
        //    var entity = new ServiceEntity(serviceID);
        //    if(!entity.IsNew)
        //    {
        //        return entity.ServiceName;
        //    }
        //    return string.Empty;
        //}

        //public string GetDocumentName(Guid id)
        //{
        //    var entity = new DocumentEntity(id);
        //    if(!entity.IsNew)
        //    {
        //        return entity.FileName;
        //    }
        //    return string.Empty;
        //}



        public string GetImageUrl(string imagePath)
        {
            //return ResolveUrl(FileImageFolder + imagePath);
            return ResolveUrl(FileUploadFolder + imagePath);
        }

        public string GetStringByParameter(string strParameterName)
        {
            if (Request.QueryString[strParameterName] != null)
            {
                return Request.QueryString[strParameterName];
            }

            return string.Empty;
        }

        public Guid GetGuidByParameter(string strParameterName)
        {
            if (Request.QueryString[strParameterName] != null)
            {
                return new Guid(Request.QueryString[strParameterName]);
            }

            return Guid.Empty;
        }
        public int GetIntByParameter(string strParameterName)
        {
            int intParameter = 0;
            if (Request.QueryString[strParameterName] != null)
            {
                if (int.TryParse(Request.QueryString[strParameterName], out intParameter))
                {
                }
            }
            return intParameter;
        }


        #region javascript
        /// <summary>
        /// 显示消息提示
        /// </summary>
        /// <param name="message">提示信息内容</param>
        public virtual void Alert(string message)
        {
            Alert(message, null);
        }
        public virtual void Alert(string message, Control focusControl)
        {
            if (string.IsNullOrEmpty(message))
            {
                throw new ArgumentNullException("message");
            }
            string script;
            if (focusControl == null)
            {
                script = string.Format("$alert('{0}');", message);
            }
            else
            {
                script = string.Format("$alert('{0}',function(){{$get('{1}').focus();}});", message,
                                       focusControl.ClientID);
            }
            ScriptStartup(script);
        }

        public virtual void ShowError(string message)
        {
            if (string.IsNullOrEmpty(message))
            {
                throw new ArgumentNullException("message");
            }
            ScriptStartup("$error('" + message + "');");
        }

        /// <summary>
        /// Show success message.
        /// </summary>
        /// <param name="message">The message.</param>
        public virtual void Success(string message)
        {
            Success(message, string.Empty);
        }

        /// <summary>
        /// 显示成功提示
        /// </summary>
        /// <param name="message">提示信息内容</param>
        /// <param name="redirectUrl">The redirect URL.</param>
        public virtual void Success(string message, string redirectUrl)
        {
            if (string.IsNullOrEmpty(message))
            {
                throw new ArgumentNullException("message");
            }
            string script;
            if (!string.IsNullOrEmpty(redirectUrl))
            {
                script = string.Format("$success('{0}',function(){{ window.location='{1}';}});",
                                        message, ResolveUrl(redirectUrl));
            }
            else
            {
                script = string.Format("$success('{0}');", message);
            }
            ScriptStartup(script);
        }

        /// <summary>
        /// 返回窗口的数据并关闭当前的窗口。
        /// </summary>
        /// <param name="value">窗口的返回值</param>
        public virtual void CloseWindow(object value)
        {
            if (value != null)
            {
                ScriptStartup(string.Format("window.returnValue ={0}; window.$close();",
                                            new JavaScriptSerializer().Serialize(value)));
            }
            else
            {
                ScriptStartup("window.$close();");
            }
        }

        /// <summary>
        /// 关闭当前的窗口。
        /// </summary>
        public virtual void CloseWindow()
        {
            CloseWindow(null);
        }

        /// <summary>
        /// 写客户端脚本(RegisterStartupScript)
        /// </summary>
        /// <param name="content">脚本内容</param>
        /// <remarks>此方法会在页面的结尾处加入javascript脚本块，用于在页面加载完成后的客户端数据初始化</remarks>
        public void ScriptStartup(string content)
        {
            string script = content.Replace("\r", @"\r").Replace("\n", @"\n");
            ScriptManager manager = ScriptManager.GetCurrent(Page);
            if (manager != null && manager.IsInAsyncPostBack)
            {
                ScriptManager.RegisterStartupScript(Page, GetType().BaseType, Guid.NewGuid().ToString(), script, true);
            }
            else
            {
                ClientScript.RegisterStartupScript(GetType().BaseType, Guid.NewGuid().ToString(), script, true);
            }
        }

        public bool ValidatePermission(string strActionName)
        {
            var collection = new RoleActionCollection();
            collection.GetMulti(RoleActionFields.ActionId == strActionName);

            var roleList = from item in collection select item.RoleId;
            var fielCompare = new FieldCompareRangePredicate(UserRoleFields.RoleId, false, roleList.ToArray());

            var condition = new PredicateExpression();
            condition.Add(UserRoleFields.UserId == CurrentLoginUser.UserID);
            condition.Add(fielCompare);
            var roleCollection = new UserRoleCollection();
            roleCollection.GetMulti(condition);

            return roleCollection.Count > 0;
        }

        #endregion

        #region page envent

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (!IsPostBack)
            {
                this.SetPageResource();
            }
        }

        protected override void OnPreInit(EventArgs e)
        {
            if (CurrentLoginUser.UserID == 0)
            {
                MenuLoaded = false;
                Response.Redirect("~/login.aspx");
            }
            HttpContext.Current.Session["CurrentFunctionID"] = CurrentFunction;

            base.OnPreInit(e);
        }

        protected override void InitializeCulture()
        {
            if (!String.IsNullOrEmpty(CurrentCulture))
            {
                base.InitializeCulture();
                //UICulture - 决定了采用哪一种本地化资源，也就是使用哪种语言
                //Culture - 决定各种数据类型是如何组织，如数字与日期
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(CurrentCulture);
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(CurrentCulture);
            }
        }

        public void ReloadCulture()
        {
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(CurrentCulture);
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(CurrentCulture);
        }

        protected override void OnLoad(System.EventArgs e)
        {
            AddEventByPage();
            base.OnLoad(e);
            

        }

        protected override void OnError(EventArgs e)
        {
            Exception ex = Server.GetLastError();
            throw new Exception(ex.Message);
            base.OnError(e);
        }

        #endregion

        #region  multi language
        /// <summary>
        /// 设置页面的多语言
        /// </summary>
        public void SetPageResource()
        {
            Control objHtmlFormControl = GetFormInPageControls();
            if (objHtmlFormControl != null)
            {
                this.GetChildControl(objHtmlFormControl, false, "");
            }
        }


        /// <summary>
        /// 得到HtmlForm(Page对象中需要多语言的部分)
        /// </summary>
        /// <returns></returns>
        protected Control GetFormInPageControls()
        {
            Control htmlFormControl = null;

            foreach (Control con in this.Controls)
            {
                if (con.GetType() == typeof(System.Web.UI.HtmlControls.HtmlForm))
                {
                    htmlFormControl = con;
                    break;
                }
            }
            if (htmlFormControl == null)
            {
                //throw new Exception("Can not find Server side Form!");
            }
            return htmlFormControl;
        }

        private string GetControlID(System.Web.UI.Control control, bool isUserControl, string userControlName)
        {
            string controlID = string.Empty;
            if (control == null || control.ID == null)
            {
                controlID = string.Empty;
            }
            else
            {
                controlID = isUserControl ? userControlName + control.ID : control.ID;
            }
            return controlID;
        }

        /// <summary>
        ///  设置子控件的资源，本方法有递归运算
        /// </summary>
        /// <param name="parentControl"></param>
        /// <param name="isUserControl"></param>
        /// <param name="userControlName"></param>
        private void GetChildControl(System.Web.UI.Control parentControl, bool isUserControl, string userControlName)
        {
            for (int i = 0; i < parentControl.Controls.Count; i++)
            {
                if (parentControl.Controls[i] == null)
                {
                    continue;
                }

                if (parentControl.Controls[i] is System.Web.UI.WebControls.Button || parentControl.Controls[i].GetType().IsSubclassOf(typeof(System.Web.UI.WebControls.Button)))
                {

                    Button control = (System.Web.UI.WebControls.Button)parentControl.Controls[i];
                    control.Text = GetResourceString(GetControlID(control, isUserControl, userControlName), isUserControl, control.Text);
                }
                else if (parentControl.Controls[i].GetType().FullName == "System.Web.UI.WebControls.Literal")
                {
                    Literal control = (System.Web.UI.WebControls.Literal)parentControl.Controls[i];
                    control.Text = GetResourceString(GetControlID(control, isUserControl, userControlName), isUserControl, control.Text);
                }

                else if (parentControl.Controls[i].GetType().FullName == "System.Web.UI.WebControls.Label" || parentControl.Controls[i].GetType().FullName == "Anthem.Label")
                {
                    Label control = (System.Web.UI.WebControls.Label)parentControl.Controls[i];
                    control.Text = GetResourceString(GetControlID(control, isUserControl, userControlName), isUserControl, control.Text);
                }

                else if (parentControl.Controls[i].GetType().FullName == "System.Web.UI.WebControls.LinkButton" || parentControl.Controls[i].GetType().FullName == "Anthem.LinkButton")
                {
                    LinkButton control = (System.Web.UI.WebControls.LinkButton)parentControl.Controls[i];
                    control.Text = GetResourceString(GetControlID(control, isUserControl, userControlName), isUserControl, control.Text);
                }
                else if (parentControl.Controls[i].GetType().FullName == "System.Web.UI.WebControls.RadioButton" || parentControl.Controls[i].GetType().FullName == "Anthem.RadioButton")
                {
                    if (!parentControl.GetType().FullName.Equals("System.Web.UI.WebControls.RadioButtonList"))
                    {
                        RadioButton control = (System.Web.UI.WebControls.RadioButton)parentControl.Controls[i];
                        control.Text = GetResourceString(GetControlID(control, isUserControl, userControlName), isUserControl, control.Text);
                    }
                }
                else if (parentControl.Controls[i].GetType().FullName == "System.Web.UI.WebControls.HyperLink")
                {
                    HyperLink control = (System.Web.UI.WebControls.HyperLink)parentControl.Controls[i];
                    control.Text = GetResourceString(GetControlID(control, isUserControl, userControlName), isUserControl, control.Text);
                }

                else if (parentControl.Controls[i].GetType().FullName == "System.Web.UI.WebControls.CheckBox" || parentControl.Controls[i].GetType().FullName == "Anthem.CheckBox")
                {
                    if (!parentControl.GetType().FullName.Equals("System.Web.UI.WebControls.CheckBoxList") && !parentControl.GetType().IsSubclassOf(typeof(System.Web.UI.WebControls.CheckBoxList)))
                    {
                        CheckBox control = (System.Web.UI.WebControls.CheckBox)parentControl.Controls[i];
                        control.Text = GetResourceString(GetControlID(control, isUserControl, userControlName), isUserControl, control.Text);
                    }
                }
                else if (parentControl.Controls[i].GetType().FullName == "System.Web.UI.HtmlControls.HtmlInputButton")
                {
                    HtmlInputButton control = (System.Web.UI.HtmlControls.HtmlInputButton)parentControl.Controls[i];
                    control.Value = GetResourceString(GetControlID(control, isUserControl, userControlName), isUserControl, control.Value);
                }
                else if (parentControl.Controls[i].GetType().FullName == "System.Web.UI.HtmlControls.HtmlInputButton")
                {
                    HtmlInputButton control = (System.Web.UI.HtmlControls.HtmlInputButton)parentControl.Controls[i];
                    control.Value = GetResourceString(GetControlID(control, isUserControl, userControlName), isUserControl, control.Value);
                }

                else if (parentControl.Controls[i].GetType().FullName == "System.Web.UI.WebControls.DataGrid" || parentControl.Controls[i] is System.Web.UI.WebControls.DataGrid || parentControl.Controls[i].GetType().FullName == "Anthem.DataGrid")
                {
                    System.Web.UI.WebControls.DataGrid gv = (System.Web.UI.WebControls.DataGrid)parentControl.Controls[i];
                    for (int j = 0; j < gv.Columns.Count; j++)
                    {
                        gv.Columns[j].HeaderText = GetResourceString(userControlName + gv.ID + ".Column" + j.ToString(), isUserControl, gv.Columns[j].HeaderText);
                    }

                    //try
                    //{
                    //    gv.DataBind();
                    //}
                    //catch
                    //{
                    //}
                    //gv.DataBind();
                }
                else if (parentControl.Controls[i].GetType().FullName == "System.Web.UI.WebControls.GridView" || parentControl.Controls[i] is System.Web.UI.WebControls.GridView)
                {
                    System.Web.UI.WebControls.GridView gv = (System.Web.UI.WebControls.GridView)parentControl.Controls[i];
                    for (int j = 0; j < gv.Columns.Count; j++)
                    {
                        gv.Columns[j].HeaderText = GetResourceString(userControlName + gv.ID + ".Column" + j.ToString(), isUserControl, gv.Columns[j].HeaderText);
                    }

                    //try
                    //{
                    //    gv.DataBind();
                    //}
                    //catch
                    //{
                    //}
                }


                if (parentControl.Controls[i].Controls.Count > 0)
                {
                    //用户自定义控件
                    if (parentControl.Controls[i].GetType().FullName.IndexOf("ASP.") != -1)
                    {
                        string userControl = parentControl.Controls[i].GetType().BaseType.Name + ".";
                        this.GetChildControl(parentControl.Controls[i], true, userControl);
                    }
                    else
                    {
                        if (parentControl.Controls[i].GetType().FullName != "System.Web.UI.WebControls.GridViewRow")
                        {
                            this.GetChildControl(parentControl.Controls[i], isUserControl, userControlName);
                        }
                    }
                }
            }
        }


        /// <summary>
        /// 根据关键字获取当前页面的多语言资源字符串
        /// </summary>
        /// <param name="p_strName">关键字</param>
        /// <returns>多语言资源字符串。如果不存在该多语言资源返回 null。</returns>
        public virtual string GetResourceString(string controlID, bool isUserControl, string oldText)
        {
            string resource = string.Empty;
            string resourcekey = string.Empty;

            if (isUserControl)
            {
                resourcekey = this.GetType().BaseType.Assembly.GetName().Name + "." + controlID;
            }
            else
            {
                resourcekey = this.GetType().BaseType.FullName + "." + controlID;
            }
            resource = GlossaryManager.GetString(resourcekey, this.CurrentCulture);
            #region 在ResouceTable表中产生没有实现多元言的控件的Key，和初始值
            //#if (DEBUG)
            //            if (resource.Trim().Length == 0)
            //            {
            //                string resourcekey1 = string.Empty;
            //                if (isUserControl)
            //                {
            //                    resourcekey1 = this.GetType().BaseType.Assembly.GetName().Name + "." + controlID;
            //                }
            //                else
            //                {
            //                    resourcekey1 = this.GetType().BaseType.FullName + "." + controlID;
            //                }
            //                GlossaryManager.AddGlossary(resourcekey1, this.CurrentCulture, oldText, this.GetType().BaseType.FullName);
            //            }
            //#endif
            #endregion
            resource = (resource.Trim().Length == 0 ? oldText : resource.Trim());
            return resource;
        }
        #endregion

        #region output the file bytes

        public void ExportFile(string strFilePath, string strFileName)
        {
            if (strFilePath != null)
            {
                var buffer = System.IO.File.ReadAllBytes(strFilePath);
                Response.AddHeader("Content-Disposition",
                                   "attachment;filename=\"" + Server.UrlDecode(strFileName) + "\"");
                Response.AddHeader("Content-Length", buffer.Length.ToString());
                Response.ContentType = "application/octet-stream;charset=utf-8";
                Response.BinaryWrite(buffer);
            }
        }
        #endregion

        #region crystal report config
        public void SetReportConfig(ReportDocument reportDocument, SqlConnectionStringBuilder connectionString)
        {
            var info = new ConnectionInfo
            {
                UserID = connectionString.UserID,
                Password = connectionString.Password,
                ServerName = connectionString.DataSource,
                DatabaseName = connectionString.InitialCatalog,
                IntegratedSecurity = connectionString.IntegratedSecurity,
                Type = ConnectionInfoType.SQL
            };

            foreach (CrystalDecisions.CrystalReports.Engine.Table table in reportDocument.Database.Tables)
            {
                var logonInfo = table.LogOnInfo;
                logonInfo.ConnectionInfo = info;
                table.ApplyLogOnInfo(logonInfo);
            }

            if (!reportDocument.IsSubreport)
            {
                foreach (ReportDocument subreport in reportDocument.Subreports)
                {
                    SetReportConfig(subreport, connectionString);
                }
            }

        }


        public static void SetParameters(ReportDocument reportDocument, IDictionary<string, object> parameters)
        {
            if (parameters == null || parameters.Count == 0)
            {
                return;
            }
            for (int i = 0; i < reportDocument.ParameterFields.Count; i++)
            {
                var fieldName = reportDocument.ParameterFields[i].Name;
                if (parameters.ContainsKey(fieldName))
                {
                    reportDocument.SetParameterValue(fieldName, parameters[fieldName]);
                }
            }
        }
        #endregion


        #region  top 菜单事件

        protected LinkButton btnNewItem;
        protected LinkButton btnEdit;
        protected LinkButton btnDelete;
        protected LinkButton btnPrint;
        protected LinkButton btnExport;
        protected LinkButton btnConfirm;

        private void AddEventByPage()
        {

            btnNewItem = Master.FindControl("btnAddNew") as System.Web.UI.WebControls.LinkButton;
            if (btnNewItem != null)
            {
                btnNewItem.Click += new EventHandler(btnNewItem_Click);
                btnNewItem.Visible = true;
            }

            btnEdit = Master.FindControl("btnEdit") as System.Web.UI.WebControls.LinkButton;
            if (btnEdit != null)
            {
                btnEdit.Click += new EventHandler(btnEdit_Click);
                btnEdit.Visible = true;
            }

            btnDelete = Master.FindControl("btnDelete") as System.Web.UI.WebControls.LinkButton;
            if (btnDelete != null)
            {
                btnDelete.Click += new EventHandler(btnDelete_Click);
                btnDelete.Visible = true;
            }

            btnPrint = Master.FindControl("btnPrint") as System.Web.UI.WebControls.LinkButton;
            if (btnPrint != null)
            {
                btnPrint.Click += new EventHandler(btnPrintm_Click);
                btnPrint.Visible = true;
            }

            btnExport = Master.FindControl("btnExport") as System.Web.UI.WebControls.LinkButton;
            if (btnExport != null)
            {
                btnExport.Click += new EventHandler(btnExport_Click);
                btnExport.Visible = true;
            }

            btnConfirm = Master.FindControl("btnConfirm") as System.Web.UI.WebControls.LinkButton;
            if (btnConfirm != null)
            {
                btnConfirm.Click += new EventHandler(btnConfirm_Click);
                btnConfirm.Visible = true;
            }

        }
        protected void btnEdit_Click(object sender, EventArgs e)
        {
            var intHeaderID = GetIntByParameter("ID");
            if (intHeaderID > 0)
            {
                var reportHeader = new ReportHeaderEntity(intHeaderID);
                if (!reportHeader.IsNew)
                {
                    RediretResolveUrl(reportHeader.ReportCategory.CreationUrl + "?ID=" + intHeaderID);
                }
            }
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            var intHeaderID = GetIntByParameter("ID");
            if (intHeaderID > 0)
            {
                var reportHeader = new ReportHeaderEntity(intHeaderID);
                if (!reportHeader.IsNew)
                {
                    reportHeader.IsActive = false;
                    if (reportHeader.Save())
                    {
                        RediretResolveUrl(SiteUrls.Report.MyReportHistory);
                    }
                }
            }
        }
        protected void btnPrintm_Click(object sender, EventArgs e)
        {
        }
        protected void btnExport_Click(object sender, EventArgs e)
        {
        }
        protected void btnConfirm_Click(object sender, EventArgs e)
        {
            RediretResolveUrl(SiteUrls.Report.ReportConfirm+"?ID="+GetStringByParameter("ID"));
        }
        protected virtual void btnNewItem_Click(object sender, EventArgs e)
        {
            RediretResolveUrl(GetPageUrl());
        }

        private string GetPageNameByAttributes()
        {
            switch (CurrentFunction)
            {
                case "OP_Columns":
                    return "Column";
                case "OP_Tables":
                    return "Table";
                case "OP_Projects":
                    return "Project";
                case "OP_Config":
                    return "Configuration";
                default:
                    return string.Empty;
            }

        }

        public virtual string GetPageUrl()
        {

            return string.Empty;

        }

        protected void SetButtonEnabled()
        {
            var reportHeaderID = GetIntByParameter("ID");
            if (reportHeaderID != 0)
            {

                var boolAdd = false;
                var boolChange = false;
                var boolConfirm = false;
                var boolExport = false;
                var boolPrint = false;
                var boolRemove = false;


                PermissionBusiness.CheckButtonVisible(CurrentLoginUser.UserID, reportHeaderID, ref boolAdd, ref   boolChange, ref   boolConfirm, ref   boolExport, ref   boolPrint, ref   boolRemove);

                btnNewItem.Enabled = boolAdd;
                btnEdit.Enabled = boolChange;
                btnDelete.Enabled = boolRemove;
                btnPrint.Enabled = boolPrint;
                btnExport.Enabled = boolExport;
                btnConfirm.Enabled = boolConfirm;
            }
        }
        protected bool CheckPageEventPermission(int buttonPermissionType)
        {
            var reportHeaderID = GetIntByParameter("ID");
            if (reportHeaderID != 0)
            { 
                var boolAdd = false;
                var boolChange = false;
                var boolConfirm = false;
                var boolExport = false;
                var boolPrint = false;
                var boolRemove = false;


                PermissionBusiness.CheckButtonVisible(CurrentLoginUser.UserID, reportHeaderID, ref boolAdd, ref   boolChange, ref   boolConfirm, ref   boolExport, ref   boolPrint, ref   boolRemove);

                btnNewItem.Enabled = boolAdd;
                btnEdit.Enabled = boolChange;
                btnDelete.Enabled = boolRemove;
                btnPrint.Enabled = boolPrint;
                btnExport.Enabled = boolExport;
                btnConfirm.Enabled = boolConfirm;

       
                switch (buttonPermissionType)
                {
                    case DictionaryCategoryConst.ButtonPermission.Add:
                        return boolAdd;
                        break;
                    case DictionaryCategoryConst.ButtonPermission.Change:
                        return boolChange;
                        break;
                    case DictionaryCategoryConst.ButtonPermission.Confirm:
                        return boolConfirm;
                        break;
                    case DictionaryCategoryConst.ButtonPermission.Export:
                        return boolExport;
                        break;
                    case DictionaryCategoryConst.ButtonPermission.Print:
                        return boolPrint;
                        break;
                    case DictionaryCategoryConst.ButtonPermission.Remove :
                        return boolRemove;
                        break;
                     
                      
                }
            }
            return false;
        }

        

        #endregion

        #region  auto bind grid column
        protected void GenerateGridColumnByActionID(VitalShining.WebControls.GridView gridList)
        {
            if (gridList.Columns.Count <= 3)
            {
                var sort = new SortExpression {ActionGridColumnFields.SortIndex | SortOperator.Ascending};
                var gridColumnCollection = new ActionGridColumnCollection();
                gridColumnCollection.GetMulti(ActionGridColumnFields.ActionId == CurrentFunction & ActionGridColumnFields.IfShow == true,0, sort);

                foreach (ActionGridColumnEntity gridColumn in gridColumnCollection)
                {
                    if (gridColumn.ColumnType == ColumnType.ColumnString.Value)
                    {
                        var NewBoundField = new System.Web.UI.WebControls.BoundField()
                        {
                            HeaderText = gridColumn.HeaderText,
                            DataField = gridColumn.ColumnName
                        };
                        gridList.Columns.Add(NewBoundField);
                    }

                    //如果是 数据字典类型，则绑定时从数据字典中取值
                    if (gridColumn.ColumnType == ColumnType.ColumnPublicItem.Value)
                    {
                        var newTemplateField = new System.Web.UI.WebControls.TemplateField()
                        {
                            HeaderText = gridColumn.HeaderText,
                        };
                        newTemplateField.ItemTemplate = new GridTemplate(gridColumn.ColumnName,gridColumn.TypeValue,null,null,null);
                        gridList.Columns.Add(newTemplateField);
                    }

                    //如果是 关联的数据表，则绑定时从关联数据表中得到search 字段
                    if (gridColumn.ColumnType == ColumnType.ColumnRelativeTable.Value)
                    {

                        //var fieldMain = GetFieldByTableColumnName(gridColumn.RelativeTable, gridColumn.RelativeColumn);
                        //    if (fieldMain != null)
                        //    {
                        //        var list = GetColumnListByTableColumnName(entity.RelativeTable,
                        //                                                  entity.RelativeColumn, entity.RelativeSearchColumn, txtCondition.Text.Trim());

                        //        var userFieldCompare = new FieldCompareRangePredicate((EntityField)fieldMain,
                        //                                                              list.ToArray());
                        //        condition.Add(userFieldCompare);
                        //    }

                            var newTemplateField = new System.Web.UI.WebControls.TemplateField()
                            {
                                HeaderText = gridColumn.HeaderText,
                            };
                            newTemplateField.ItemTemplate = new GridTemplate(gridColumn.ColumnName, string.Empty, gridColumn.RelativeTable, gridColumn.RelativeColumn, gridColumn.RelativeSearchColumn);
                            gridList.Columns.Add(newTemplateField);
                    }


                    //if (gridColumn.ColumnType == ColumnType.ColumnPublicItem.Value)
                    //{
                    //    var NewBoundField = new System.Web.UI.WebControls.BoundField()
                    //                            {
                    //                                HeaderText = gridColumn.HeaderText,
                    //                                DataField = gridColumn.ColumnName
                    //                            };
                    //    gridList.Columns.Add(NewBoundField); 
                    //}

                    //if (gridColumn.ShowType == DictionaryCategoryConst.GridColumnType.EditButtom)
                    //{
                    //    var newTemplateField = new System.Web.UI.WebControls.TemplateField()
                    //    {
                    //        HeaderText = gridColumn.HeaderText, 
                    //    };


                    //    newTemplateField.ItemTemplate = new GridTemplate(DictionaryCategoryConst.GridColumnType.EditButtom);

                    //    gridList.Columns.Add(newTemplateField);
                    //}
                    
                }
            }

        }

        public class GridTemplate : ITemplate
        {
            public string ColumnName
            {
                get;
                set;
            }
            public string DictCategoryID
            {
                get; set;
            }

                 public string RelativeTable
            {
                get; set;
            }

                 public string RelativeColumn
            {
                get; set;
            }

                 public string RelativeSearchColumn
            {
                get; set;
            }


            

            public string KeyIDName
            {
                get;
                set;
            }

            /// <summary>
            /// 
            /// </summary>
            /// <param name="dictCategoryID">数据字典类型ID</param>
            public GridTemplate(string strColumnName,string dictCategoryID,string strRelativeTable, string strRelativeColumn, string strRelativeSearchColumn)
            {
                ColumnName = strColumnName;
                DictCategoryID = dictCategoryID;
                RelativeTable = strRelativeTable;
                RelativeColumn = strRelativeColumn;
                RelativeSearchColumn = strRelativeSearchColumn; 
            }

            public void InstantiateIn(System.Web.UI.Control container)  //实现此方法，实现动态绑定，也可以给mytemplate 增加重载方法  myTemplate（string type） 来区分需要动态绑定的控件（如 dropdownlist，label 等）
            {
                if(!string.IsNullOrEmpty(DictCategoryID))
                {
                    var label = new Label(); 
                    label.DataBinding += new EventHandler(BindPublicItem);  //给控件增加动态绑定事件，此事件会在grid data bound 中执行，不需要手动执行
                    container.Controls.Add(label);
                }


                if (!string.IsNullOrEmpty(RelativeTable))
                {
                    var label = new Label();
                    label.DataBinding += new EventHandler(BindRelativeTableColumn);  //给控件增加动态绑定事件，此事件会在grid data bound 中执行，不需要手动执行
                    container.Controls.Add(label);
                }  
            }

            private void BindPublicItem(Object sender, EventArgs e)
            {
                Label lblSender = (Label)sender;
                GridViewRow container = (GridViewRow)lblSender.NamingContainer;
              var intPublicItem= (int)DataBinder.Eval(container.DataItem, ColumnName);
              lblSender.Text = AdminBusiness.GetDataName(intPublicItem);
            }


            private void BindRelativeTableColumn(Object sender, EventArgs e)
            { 
                Label lblSender = (Label)sender;
                GridViewRow container = (GridViewRow)lblSender.NamingContainer;
                //var intGridColumnValue= (int)DataBinder.Eval(container.DataItem, ColumnName);  // item 类型 由table 主键决定
                //lblSender.Text = intGridColumnValue.ToString();

                var strColumnName = RelativeTable + "." + RelativeSearchColumn;
                lblSender.Text = DataBinder.Eval(container.DataItem, strColumnName).ToString();

            } 
        }


        public IEntityField GetFieldByTableColumnName(string strTableName, string strColumnName)
        {

            var entity = GetEntityByTableName(strTableName);
            for (int i = 0; i < entity.Fields.Count; i++)
            {
                if (entity.Fields[i].Name.ToUpper() == strColumnName.ToUpper())
                {
                    return entity.Fields[i];
                }
            }
            return null;
        }


        private CommonEntityBase GetEntityByTableName(string strTableName)
        {
            switch (strTableName)
            {
                case "Action":
                    return new ActionEntity();
                //case "Department":
                //    return new DepartmentEntity();
                //case "User":
                //    return new UserEntity();
                //case "Employee":
                //    return new EmployeeEntity();
            }
            return null;
        }


        public List<object> GetColumnListByTableColumnName(string strTableName, string strColumnName, string strSearchColumnName, string strCondition)
        {
            var field = (EntityField)GetFieldByTableColumnName(strTableName, strSearchColumnName);
            var condition = new PredicateExpression();
            condition.Add(field % ("%" + strCondition + "%"));

            var listReturn = new List<object>();
            switch (strTableName)
            {
                case "Action":
                    var actionCollection = new ActionCollection();
                    actionCollection.GetMulti(condition);
                    foreach (var item in actionCollection)
                    {
                        listReturn.Add(item.GetFieldByName(strColumnName).CurrentValue);
                    }
                    return listReturn;
                //case "Department":
                //   var departmentCollection = new DepartmentCollection();
                //   departmentCollection.GetMulti(condition);
                //   foreach (var item in departmentCollection)
                //   {
                //       listReturn.Add(item.GetFieldByName(strColumnName).CurrentValue);
                //   }
                //   return listReturn;
                //case "User":
                //   var userCollection = new UserCollection();
                //   userCollection.GetMulti(condition);
                //   foreach (var item in userCollection)
                //   {
                //       listReturn.Add(item.GetFieldByName(strColumnName).CurrentValue);
                //   }
                //   return listReturn;
                //case "Employee":
                //   var employeeCollection = new EmployeeCollection();
                //   employeeCollection.GetMulti(condition);
                //   foreach (var item in employeeCollection)
                //   {
                //       listReturn.Add(item.GetFieldByName(strColumnName).CurrentValue);
                //   }
                //   return listReturn;
            }
            return null;
        }

        #endregion
    }

    public class ApplicationImages
    {
        public const string PageFirst = "~/Images/Pager/Page_First.gif";
        public const string PageFirstGray = "~/Images/Pager/Page_First_Gray.gif";
        public const string PagePrevious = "~/Images/Pager/Page_Previous.gif";
        public const string PagePreviousGray = "~/Images/Pager/Page_Previous_Gray.gif";
        public const string PageNext = "~/Images/Pager/Page_Next.gif";
        public const string PageNextGray = "~/Images/Pager/Page_Next_Gray.gif";
        public const string PageLast = "~/Images/Pager/Page_Last.gif";
        public const string PageLastGray = "~/Images/Pager/Page_Last_Gray.gif";

        public const string TreeNodeOpened = "~/Images/Folder/Folder_open.gif";
        public const string TreeNodeClosed = "~/Images/Folder/Folder_close.gif";

    }

    public class GenerateAlert
    {
        public const string SaveFailed = "Save Failed!";
        public const string SavSuccess = "Successfully saved!";
    }



    public class ColumnType
    {



        public static ColumnTypeEntity Empty
        {
            get
            {
                return new ColumnTypeEntity
                {
                    Name = "-",
                    Value = ""
                };
            }
        }

        public static ColumnTypeEntity ColumnInt
        {
            get
            {
                return new ColumnTypeEntity
                {
                    Name = "Int",
                    Value = "Int"
                };
            }
        }


        public static ColumnTypeEntity ColumnString
        {
            get
            {
                return new ColumnTypeEntity
                {
                    Name = "String",
                    Value = "String"
                };
            }
        }


        public static ColumnTypeEntity ColumnPublicItem
        {
            get
            {
                return new ColumnTypeEntity
                {
                    Name = "Public Item",
                    Value = "PublicItem"
                };
            }
        }
        public static ColumnTypeEntity ColumnRelativeTable
        {
            get
            {
                return new ColumnTypeEntity
                {
                    Name = "Related Table",
                    Value = "RelatedTable"
                };
            }
        }

        public static ColumnTypeEntity ColumnMultiSelect
        {
            get
            {
                return new ColumnTypeEntity
                {
                    Name = "Multi Select",
                    Value = "MultiSelect"
                };
            }
        }
    }



    public class ColumnTypeEntity
    {
        public string Name { get; set; }
        public string Value { get; set; }
    }



}
